package com.pek.util;

import com.pek.control.entity.UserEntity;
import com.pek.control.util.RedisUtil;

public abstract class Constants {
    /**
     * 随机数
     * @param size 长度
     * @return 随机数
     */
    public static String random(int size) {
        String[] letters = {
                "A", "B", "C",
                "D", "E", "F",
                "G", "H", "I",
                "J", "K", "L",
                "M", "N", "O",
                "P", "Q", "R",
                "S", "T", "U",
                "V", "W", "X",
                "Y", "Z", "0",
                "1", "2", "3",
                "4", "5", "6",
                "7", "8", "9",
        };
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < size; i++) {
            result.append(letters[(int) (Math.random() * letters.length)]);
        }
        return result.toString();
    }

    /**
     * 生成token 并删除旧token
     */
    public static String spawnToken(UserEntity user, RedisUtil redisUtil){
        String token = "UT-" + user.getUsername() + "-" + System.currentTimeMillis() + "-" + Constants.random(7);
        if (!redisUtil.scan("UT-" + user.getUsername() + "*").isEmpty()) {
            redisUtil.delete("UT-" + user.getUsername() + "*");
        }
        return token;
    }
}
